package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.GreeTextScan;
import com.heima.comment.dtos.CommentDto;
import com.heima.comment.dtos.CommentLikeDto;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.comment.vo.ApCommentVo;
import com.heima.feigns.user.UserFeign;
import com.heima.model.common.constants.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    UserFeign userFeign;
    @Autowired
    GreeTextScan greeTextScan;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    CommentHotService hotService;

    @Autowired
    KafkaTemplate kafkaTemplate;
    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //参数校验
        if (dto == null || dto.getCommentId() == null || dto.getOperation() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询评论   根据id进行查询
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "相关评论信息已经不存在,无法进行点赞操作");
        }

        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            //未登錄無法點贊
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "登錄后才可以进行点赞操作");
        }
        ApUser userById = userFeign.findUserById(user.getId());
        if (userById == null) {
            //如果當前登錄的賬號查詢不到也不可以进行点赞操作
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到当前登录的账号信息");
        }

        //评论存在且当前账号没有对此评论点赞则可以点赞
        ApCommentLike apCommentLike = mongoTemplate.findOne(Query.query(
                Criteria.where("authorId").is(userById.getId())
                        .and("commentId").is(dto.getCommentId()))
                , ApCommentLike.class);
        //当前的点赞操作存在且是点赞状态,非法操作,全部判断完毕
        if ((apCommentLike != null && apCommentLike.getOperation() == 0 && dto.getOperation() == 0)
                || (apCommentLike != null && apCommentLike.getOperation() == 1 && dto.getOperation() == 1)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.ILLEGAL_OPERATION, "无法进行重复点赞(或者取消点赞)操作");
        }
        if (apCommentLike == null) {
            apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(userById.getId());
            apCommentLike.setCommentId(dto.getCommentId());
        }
        apCommentLike.setOperation(dto.getOperation());
        mongoTemplate.save(apCommentLike);//保存当前的点赞行为信息

        //这里都是合法状态
        if (dto.getOperation() == 1) {
            apComment.setLikes(apComment.getLikes() - 1 < 0 ? 0 : apComment.getLikes() - 1);
        } else apComment.setLikes(apComment.getLikes() + 1);

        mongoTemplate.save(apComment);

        //当前为普通评论并且当前的点赞数量大于5
        if (apComment.getFlag().intValue() == 0 && apComment.getLikes() > 5) {
            //執行這個什麽判斷並增加熱點兒評論的方法
            hotService.hotCommentExecutor(apComment);
        }


        //返回的是点赞数
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes", apComment.getLikes());
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 保存评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null
                || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "文本内容过长,请缩减后提交");
        }
        ApUser userById = AppThreadLocalUtils.getUser();
        if (userById == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        ApUser user = userFeign.findUserById(userById.getId());
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "当前登录状态异常,请重新登录");
        }
        //阿里云远程调用判断当前是否可以发布相关信息
        try {
            Map map = greeTextScan.greeTextScan(dto.getContent());
            if (map.get("suggestion").equals("block")) {
                //文章中包含敏感信息直接拒绝
                return ResponseResult.errorResult(AppHttpCodeEnum.ILLEGAL_OPERATION, "内容中包含敏感信息不可发布");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ApComment apComment = new ApComment();
        apComment.setAuthorId(user.getId());
        apComment.setAuthorName(user.getName());
        apComment.setImage(user.getImage());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short) 0);
        apComment.setFlag((short) 0);
        mongoTemplate.insert(apComment);


        //发送评论消息
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setType(UpdateArticleMess.UpdateArticleType.COMMENT);
        mess.setArticleId(dto.getArticleId());
        kafkaTemplate.send(HotArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC,
                JSON.toJSONString(mess));


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 根据文章id查询评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //每页显示10条数据
        if (dto.getSize() == null || dto.getSize() <= 0 || dto.getSize() > 50) {
            dto.setSize(10);
        }
        List<ApComment> apComments = null;

        if (dto.getIndex() == 1) {
            apComments = mongoTemplate.find(Query.query(
                    Criteria.where("entryId").is(dto.getArticleId())
                            .and("flag").is((short) 1)
                    ).limit(dto.getSize()).
                            with(Sort.by(Sort.Direction.DESC, "likes"))
                    , ApComment.class);
            List<ApComment> normalComments = mongoTemplate.find(Query.query(
                    Criteria.where("entryId").is(dto.getArticleId())
                            .and("createdTime").lt(dto.getMinDate())
                            .and("flag").is(0)
                    ).limit(dto.getSize()).
                            with(Sort.by(Sort.Direction.DESC, "createdTime"))
                    , ApComment.class);
            apComments.addAll(normalComments);
        } else {
            //按照时间倒叙进行查询,分页
            apComments = mongoTemplate.find(Query.query(
                    Criteria.where("entryId").is(dto.getArticleId())
                            .and("createdTime").lt(dto.getMinDate())
                            .and("flag").is(0)
                    ).limit(dto.getSize()).
                            with(Sort.by(Sort.Direction.DESC, "createdTime"))
                    , ApComment.class);
        }


        //沒登陸的话显示所有的評論數據並返回就可以了
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(apComments);
        }
        ApUser userById = userFeign.findUserById(user.getId());
        if (userById == null) {
            return ResponseResult.okResult(apComments);
        }
        List<String> collect = apComments.stream().map(x -> x.getId()).collect(Collectors.toList());
        //遍历当前文章的所有评论信息,去取出当前文章内所有评论的id
        //查询当前用户在当前页面中的所有已经点赞的评论
        List<ApCommentLike> myLikeApComments = mongoTemplate.find(Query.query(
                Criteria.where("commentId").in(collect)
                        .and("authorId").is(userById.getId())
                        .and("operation").is((short) 0))
                , ApCommentLike.class);


        if (apComments != null && apComments.size() > 0
                && myLikeApComments != null && myLikeApComments.size() >= 0
        ) {
            List resultList = new ArrayList();
            apComments.stream().forEach(
                    x -> {
                        ApCommentVo apCommentVo = new ApCommentVo();
                        BeanUtils.copyProperties(x, apCommentVo);
                        //查询所有当前我已点赞的评论的主键id
                        myLikeApComments.forEach(
                                myLikeApComment -> {
                                    if (x.getId().equals(myLikeApComment.getCommentId())) {
                                        apCommentVo.setOperation((short) 0);
                                    }
                                }
                        );
                        resultList.add(apCommentVo);
                    }
            );

//            for (ApComment apComment : apComments) {
//                apCommentVo.setOperation((short) 1);
//                BeanUtils.copyProperties(apComment, apCommentVo);
//
//                for (ApCommentLike myLikeApComment : myLikeApComments) {
//                    if (apComment.getId().equals(myLikeApComment.getCommentId())) {
//                        apCommentVo.setOperation((short) 0);
//                    }
//                }
//                resultList.add(apCommentVo);
//            }
            return ResponseResult.okResult(resultList);
        }
        return ResponseResult.okResult(apComments);
    }
}